package com.xuanzheng.company.service.impl;

import com.xuanzheng.company.dao.SystemApplicationDao;
import com.xuanzheng.company.dao.UserDao;
import com.xuanzheng.company.dao.impl.SystemApplicationDaoImpl;
import com.xuanzheng.company.dao.impl.UserDaoImpl;
import com.xuanzheng.company.entity.SystemApplication;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.SystemApplicationService;

import java.util.List;

public class SystemApplicationServiceImpl implements SystemApplicationService {
    private final SystemApplicationDao applicationDao;
    private final UserDao userDao;
    private final CompanyService companyService;
    
    public SystemApplicationServiceImpl() {
        this.applicationDao = new SystemApplicationDaoImpl();
        this.userDao = new UserDaoImpl();
        this.companyService = new CompanyServiceImpl();
    }

    @Override
    public boolean submitApplication(SystemApplication application) {
        return applicationDao.addApplication(application);
    }

    @Override
    public boolean reviewApplication(String id, int status, String rejectReason) {
        boolean success = applicationDao.updateApplicationStatus(id, status, rejectReason);
        
        // 如果申请通过，自动为公司负责人创建公司
        if (success && status == 1) {
            SystemApplication application = applicationDao.getApplicationById(id);
            if (application != null) {
                User user = userDao.findById(application.getUserId());
                if (user != null && user.getRole() == 1) {
                    // 创建公司
                    companyService.createCompanyFromApproval(user);
                }
            }
        }
        
        return success;
    }

    @Override
    public SystemApplication getUserLatestApplication(String userId) {
        return applicationDao.getLatestApplicationByUserId(userId);
    }

    @Override
    public int getUserApplicationStatus(String userId) {
        SystemApplication application = applicationDao.getLatestApplicationByUserId(userId);
        if (application == null) {
            return -1; // 未申请
        }
        return application.getStatus(); // 0=审核中, 1=已通过, 2=已拒绝
    }

    @Override
    public List<SystemApplication> getAllApplications() {
        return applicationDao.getAllApplications();
    }

    @Override
    public List<SystemApplication> getApplicationsByStatus(int status) {
        return applicationDao.getApplicationsByStatus(status);
    }

    @Override
    public List<SystemApplication> searchApplications(String keyword) {
        return applicationDao.searchApplications(keyword);
    }

    @Override
    public List<SystemApplication> searchApplicationsWithStatus(int status, String keyword) {
        return applicationDao.searchApplicationsWithStatus(status, keyword);
    }
} 